<?php
namespace app\api\controller;

use app\common\model\Post as P;
use app\common\validate\Post as postValidate;
use think\exception\ValidateException;
use think\facade\Db;

class Post extends Base
{
    //轮播图文章/置顶文章
    public function getConfigPost()
    {
        // carousel or topArticle
        $config = input("config");
        $carouselConfig = Db::name("system")->where("config","carousel")->value("value");
        $carouselArticle = Db::name("post")->field("id,title,cover_image")->where("status",0)->where("id","in", $carouselConfig)->select()->toArray();

        foreach ($carouselArticle as $key =>$item){
            if (strpos($item["cover_image"],"http") === false){
                if (empty($item["cover_image"])){
                    $carouselArticle[$key]["cover_image"] = request()->domain() ."/uploads/default/default_cover.jpg";
                }else{
                    $carouselArticle[$key]["cover_image"] = request()->domain() .$item["cover_image"];
                }
            }
        }
        return json($carouselArticle);
    }
    public function postAdd()
    {
        $data = input("post.");
        $data["status"] = 0;

        $order=array("\r\n","\n","\r");
        $replace='<br/>';
        $data["content"]=str_replace($order,$replace,$data["content"]);

        try {
            validate(postValidate::class)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return json(["code" => 0,"msg" =>$e->getError()]);
        }

        preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',input("content","","trim"), $ereg);//正则表达式把图片的SRC获取出来了
        if(empty($ereg)) {
            $cover_image = "";
        }else{
            $cover_image = $ereg[1];//图片SRC
        }
        $data["cover_image"] = $cover_image;
        $data["uid"] = $this->getUid($data["sessionKey"]);
        $create = P::create($data);
        if ($create){
            return json(["code" => 1,"msg" =>"投稿成功，等待管理员审核","postId" => $create->id]);
        }
        return json(["code" => 0,"msg" =>"投稿失败"]);
    }

    //最新文章
    public function newList()
    {
        $list = Db::name('post')->withoutField("content")->order("id desc")->where("status",0)->paginate(10,false,['query'=>request()->param()])->each(function($item, $key){
            if (strpos($item["cover_image"],"http") === false){
                if (empty($item["cover_image"])){
                    $item["cover_image"] = request()->domain() ."/uploads/default/default_cover.jpg";
                }else{
                    $item["cover_image"] = request()->domain() .$item["cover_image"];
                }
            }
            return $item;
        });
        return json($list);
    }

    //文章详情
    public function detail()
    {
        $id = input('id');
        Db::name('post')->where('id',$id)->inc('read_count')->update();
        $detail = P::withJoin(['userInfo'	=>	['username','uid'],'cate' =>['cate_name']])->where("tn_post.status",0)->where('id',$id)->find();
        if (!$detail){
            return json(["code" => 0,"msg" => "没有该文章"]);
        }
        if (strpos($detail["cover_image"],"http") === false){
            if (empty($detail["cover_image"])){
                $detail["cover_image"] = request()->domain() ."/uploads/default/default_cover.jpg";
            }else{
                $detail["cover_image"] = request()->domain() .$detail["cover_image"];
            }
        }
        return json($detail);
    }

    //我的文章
    public function myPost()
    {
        $openid = cache(input("sessionKey"));
        $where["uid"] = Db::name("user")->where("openid",$openid)->value("uid");
        $list = Db::name('post')->withoutField("content")->where($where)->order("id desc")->where("status",0)->paginate(10,false,['query'=>request()->param()])->each(function($item, $key){
            if (strpos($item["cover_image"],"http") === false){
                if (empty($item["cover_image"])){
                    $item["cover_image"] = request()->domain() ."/uploads/default/default_cover.jpg";
                }else{
                    $item["cover_image"] = request()->domain() .$item["cover_image"];
                }
            }
            return $item;
        });
        return json($list);
    }
    //分类文章
    public function cateArticle()
    {
        $id = input('cateId');
        $newList = Db::name('post')->order("id desc")->where("cate_id",$id)->where("status",0)->paginate(10,false,['query'=>request()->param()])->each(function($item, $key){
            if (strpos($item["cover_image"],"http") === false){
                if (empty($item["cover_image"])){
                    $item["cover_image"] = request()->domain() ."/uploads/default/default_cover.jpg";
                }else{
                    $item["cover_image"] = request()->domain() .$item["cover_image"];
                }
            }
            return $item;
        });
        return json($newList);
    }
 
    //分类列表
    public function categoryList()
    {
        $list = Db::name("category")->field(["cate_name,cate_id"])->select()->toArray();

            foreach ($list as $key=> $item){
                $list[$key]["text"] = $item["cate_name"];
                $list[$key]["value"] = $item["cate_id"];
                unset($list[$key]["cate_name"]);
                unset($list[$key]["cate_id"]);
            }
        return json($list);
    }

    public function myCollectPost()
    {
        $openid = cache(input("sessionKey"));
        $where["uid"] = Db::name("user")->where("openid",$openid)->value("uid");
        $postIds = Db::name("post_collection")->where($where)->column("post_id");
        $list = Db::name('post')->withoutField("content")->where("id","in",$postIds)->order("id desc")->where("status",0)->paginate(10,false,['query'=>request()->param()])->each(function($item, $key){
            if (strpos($item["cover_image"],"http") === false){
                if (empty($item["cover_image"])){
                    $item["cover_image"] = request()->domain() ."/uploads/default/default_cover.jpg";
                }else{
                    $item["cover_image"] = request()->domain() .$item["cover_image"];
                }
            }
            return $item;
        });
        return json($list);
    }
}